#!/usr/bin/env python3
import os
import argparse
from pathlib import Path
import shutil
import subprocess
import sys

def create_rpmbuild_dirs(base_dir: str = None, verbose: bool = False) -> None:
    """
    创建rpmbuild所需的标准目录结构
    
    参数:
        base_dir: 基础目录路径，默认为当前用户的主目录下的rpmbuild目录
        verbose: 是否显示详细输出
    """
    # 如果未指定基础目录，使用默认的 ~/rpmbuild
    if not base_dir:
        base_dir = os.path.join(str(Path.home()), "rpmbuild")
    
    # rpmbuild的标准目录列表
    rpmbuild_dirs = [
        "BUILD",
        "BUILDROOT",
        "RPMS",
        "RPMS/noarch",
        "RPMS/x86_64",  # 常见的64位架构，可根据需要修改
        "SOURCES",
        "SPECS",
        "SRPMS"
    ]
    
    # 创建基础目录
    try:
        os.makedirs(base_dir, exist_ok=True)
        if verbose:
            print(f"创建基础目录: {base_dir}")
    except OSError as e:
        print(f"无法创建基础目录 {base_dir}: {e}")
        return
    
    # 创建所有子目录
    for dir_path in rpmbuild_dirs:
        full_path = os.path.join(base_dir, dir_path)
        try:
            os.makedirs(full_path, exist_ok=True)
            if verbose:
                print(f"创建目录: {full_path}")
        except OSError as e:
            print(f"无法创建目录 {full_path}: {e}")

def clean_build_directory(directory: str, verbose: bool = False) -> None:
    """
    清理build目录
    
    参数:
        directory: 要清理的目录路径
        verbose: 是否显示详细输出
    """
    if os.path.exists(directory):
        try:
            if verbose:
                print(f"正在清理目录: {directory}")
            shutil.rmtree(directory)
            if verbose:
                print(f"成功清理目录: {directory}")
        except OSError as e:
            print(f"清理目录 {directory} 失败: {e}")
            sys.exit(1)
    else:
        if verbose:
            print(f"目录 {directory} 不存在，无需清理")

def main():
    parser = argparse.ArgumentParser(description="创建rpmbuild标准目录结构")
    parser.add_argument("-d", "--directory", default=os.path.join(os.getcwd(), "build"), help="指定rpmbuild的基础目录路径，默认为当前目录下的build目录")
    parser.add_argument("-v", "--verbose", action="store_true", help="显示详细输出")
    parser.add_argument("--clean", action="store_true", help="清理历史build目录，默认不清理")
    
    args = parser.parse_args()

    # 根据参数清理build目录
    if args.clean:
        clean_build_directory(args.directory, args.verbose)

    # 安装tree命令，用于显示目录结构
    if shutil.which('tree') is None:
        print("⚠️ tree 未安装，正在安装...")
        try:
            subprocess.run(['yum', 'install', '-y', 'tree'], check=True)
            print("✅ tree 安装成功")
        except subprocess.CalledProcessError as e:
            print("❌ tree 安装失败:", e)
            sys.exit(1)
    
    create_rpmbuild_dirs(args.directory, args.verbose)
    
    if not args.verbose:
        base_dir = args.directory or os.path.join(str(Path.home()), "rpmbuild")
        print(f"已成功创建rpmbuild目录结构在: {base_dir}")
        # 使用tree命令显示base_dir目录结构，打印tree命令的返回信息
        try:
            print("目录结构如下:")
            result = subprocess.run(['tree', base_dir], check=True, stdout=subprocess.PIPE, text=True)
            print(result.stdout)
        except subprocess.CalledProcessError as e:
            print("tree命令异常，无法显示目录结构:", e)


if __name__ == "__main__":
    main()